package pl.hexar.action;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.faces.FacesMessages;
import pl.hexar.model.TmpUser;
import pl.hexar.model.User;

@Name("activator")
public class Activator {

    @RequestParameter("code")
    String code;
    @RequestParameter("member")
    String member;
    @In()
    EntityManager entityManager;

    public void activate() {
        Query findTmpUser = entityManager.createNamedQuery("TmpUser.findByLogin");
        findTmpUser.setParameter("login", member);
        TmpUser tmpUser = new TmpUser();
        if (isAcivate(member)) {
            FacesMessages.instance().add("Konto #0 bylo aktywowane wczesniej", member);
            return;
        }
        try {
            tmpUser = (TmpUser) findTmpUser.getSingleResult();
        } catch (NoResultException nre) {
            FacesMessages.instance().add("Problem za aktywacja konta ");
            return;
        }

        if (!emptyString(code) && !emptyString(member)) {
            if (code.equals(HexarUtil.codeString(tmpUser.getLogin()))) {
                User user = new User(tmpUser.getLogin(), tmpUser.getEmail(), tmpUser.getPassword(),tmpUser.getRegDate());
                entityManager.persist(user);
                entityManager.remove(tmpUser);
                FacesMessages.instance().add("Konto  aktywne" + user.getLogin());
                return;
            }
        }
        FacesMessages.instance().add("Problem z aktywacja konta");

    }

    private boolean isAcivate(String name) {
        Query findUser = entityManager.createNamedQuery("User.findByLogin");
        findUser.setParameter("login", name);
        try {
            findUser.getSingleResult();
        } catch (NoResultException nre) {
            return false;
        }
        return true;
    }

    private boolean emptyString(String text) {
        if (!text.equals("") && text != null) {
            return false;
        }
        return true;
    }
}
